home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1529 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net   (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Q: realloc->free?
  5. Date: 14 Jan 1996 22:28:04 GMT
  6. Organization: News & Observer Public Access
  7. Message-ID: <4dc01k$ifb@castle.nando.net>
  8. References: <4daa2e$oh5@axe.netdoor.com>
  9. Reply-To: actuary@nando.net (Bill McCarthy)
  10. NNTP-Posting-Host: grail801.nando.net
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4daa2e$oh5@axe.netdoor.com>, esargent@netdoor.com (Eric Sargent) writes:
  14. >    This is probably a dumb question, but I can't find any specific or
  15. >exact information about this.  Given this:
  16. >
  17. >char *a, *b;
  18. >
  19. >a = malloc(10);
  20. >....
  21. >/*
  22. >    later we need to increase the size
  23. >*/
  24. >....
  25. >b = realloc(a, 100);
  26. >
  27. >    Now let's say realloc had to move the data so a != b.  Does realloc
  28. >free the memory previously pointed to by a or should it be explicitly
  29. >freed if realloc returns a new location?  I checked the FAQ, but there
  30. >was nothing specific about realloc.  Thanks for any information.
  31.  
  32. If realloc() is successful, it handles any freeing needed.  You may want
  33. to add, after the malloc() line:
  34.  
  35. if ( b )
  36.    a = NULL;
  37. else
  38. {
  39.    free( a );
  40.    fprintf( stderr, "Failure in realloc()\n" );
  41.    exit( EXIT_FAILURE );
  42. }
  43.  
  44. Don't ever use "a = realloc(a,n);" because of realloc() fails, you've lost
  45. the pointer to allocated memory.
  46.  
  47. Bill McCarthy
  48. actuary@nando.net
  49. Wendell, NC  USA
  50.  
  51.